package com.feibi.firstplugin.Utils;

import com.fasterxml.jackson.jr.ob.JSON;
import okhttp3.*;
import org.apache.http.util.TextUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class HttpUtil {
    static HttpUtil instance;
    OkHttpClient okHttpClient;

    public static HttpUtil getInstance() {
        if (instance == null) instance = new HttpUtil();
        return instance;
    }

    public HttpUtil() {
        init();
    }

    void init() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS).build();
    }


    /**
     * okHttp get异步请求
     *
     * @param actionUrl 接口地址
     * @param paramsMap 请求参数
     * @param callBack  请求返回数据回调
     */
    public Call requestGet(String actionUrl, HashMap<String, Object> paramsMap, HashMap<String, Object> headerMap, final HttpCallBack<String> callBack) {
        System.out.println(actionUrl);
        StringBuilder tempParams = new StringBuilder();
        try {
            int pos = 0;
            if (paramsMap != null) {
                for (String key : paramsMap.keySet()) {
                    if (pos > 0) {
                        tempParams.append("&");
                    }
                    tempParams.append(String.format("%s=%s", key, paramsMap.get(key).toString()));
                    pos++;
                }
            }
            String requestUrl = actionUrl;
            if (tempParams.length() > 0) {
                if (actionUrl.contains("?")) {
                    requestUrl = String.format("%s&%s", actionUrl, tempParams);
                } else {
                    requestUrl = String.format("%s?%s", actionUrl, tempParams);
                }
            }
            Request.Builder builder = new Request.Builder().url(requestUrl);
            if (headerMap != null) {
                for (String hKey : headerMap.keySet()) {
                    builder.addHeader(hKey, headerMap.get(hKey).toString());
                }
            }
            final Request request = builder.build();
            if (okHttpClient == null) init();
            final Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    callBack.onReqFail("请求失败" + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        callBack.onReqSuccess(string);
                    } else {
                        callBack.onReqFail("请求失败");
                    }
                }
            });
            return call;
        } catch (Exception e) {
            e.printStackTrace();
            callBack.onReqFail("请求失败" + e.getMessage());
        }
        return null;
    }

    public Call requestPost(String actionUrl, String json, HashMap<String, Object> headerMap, final HttpCallBack<String> callBack) {
        try {
            RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
            String requestUrl = String.format("%s", actionUrl);
            Request.Builder builder1 = new Request.Builder().url(requestUrl).post(formBody);
            if (headerMap != null) {
                for (String hKey : headerMap.keySet()) {
                    builder1.addHeader(hKey, headerMap.get(hKey).toString());
                }
            }
            final Request request = builder1.build();
            if (okHttpClient == null) init();
            final Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    callBack.onReqFail("请求失败" + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        callBack.onReqSuccess(string);
                    } else {
                        callBack.onReqFail("请求失败");
                    }
                }
            });
            return call;
        } catch (Exception e) {
            e.printStackTrace();
            callBack.onReqFail("请求失败" + e.getMessage());
        }
        return null;
    }

}
